//
//  AudioViewController.m
//  GC_OC
//
//  Created by  Quan He on 2022/4/17.
//

#import "AudioViewController.h"
#import "AudioListTableViewCell.h"
#define kHeaderH fkStatusAndNaBarH + 15 + 100 + 15 + 30

@interface AudioViewController ()<UITableViewDelegate, UITableViewDataSource, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, strong) NSMutableArray *titleArr;
@property (nonatomic, strong) NSMutableArray *heightArr;
@property (nonatomic, strong) ObjectAFNetWorking* objectAFNet;
@property (nonatomic, assign) NSInteger selectedIndex;
@property (nonatomic, strong) UIButton *button;

@property (nonatomic, strong) UIView *topBackView;
@property (nonatomic, strong) UIImageView *topImageView;
@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) NSString *cellClassString;
@property (nonatomic, strong) UILabel *parentLabel;

@property (nonatomic, strong) NSMutableArray *cacheList;

@end

@implementation AudioViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    self.objectAFNet = [[ObjectAFNetWorking alloc] init];
    self.dataArr = [NSMutableArray array];
    self.titleArr = [NSMutableArray array];
    self.heightArr = [NSMutableArray array];
    [self requestData];
    
}
#pragma mark - Life
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}
#pragma mark - UI
- (void)setupUI {
    self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
    
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.equalTo(self.view);
        make.top.equalTo(@(-StatusBarHeight));
    }];

    [self.view addSubview:self.headerView];

    [self.view addSubview:self.parentLabel];
    [self.parentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(@(StatusBarHeight));
        make.left.equalTo(@(45));
        make.height.equalTo(@(44));
    }];
    
    [self addBackButton];
    
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.font = [UIFont systemFontOfSize:17 weight:UIFontWeightBold];
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.text = self.title;
    titleLabel.textAlignment = NSTextAlignmentCenter;
    if (self.isMenu) {
        [self.headerView addSubview:titleLabel];
        [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(@(StatusBarHeight));
            make.right.left.equalTo(@(0));
            make.height.equalTo(@(topHeight - StatusBarHeight));
        }];
    }else {
        
        self.parentLabel.text = [NSString stringWithFormat:@"# %@ #",self.title];
    }
    
    [self.view addSubview: self.button];
    [self.button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(@(-50));
        make.width.height.equalTo(@(40));
        make.bottom.equalTo(@(-50));
    }];
}

#pragma mark - Business
- (void)fillTheData:(NSDictionary *)dic isNetRequest:(BOOL)isRequest {
    NSLog(@"%@",dic);
    NSArray *videoList;
    if (self.isMenu) {
        videoList = dic[@"data"][@"list"];
        if (videoList.count == 0 && isRequest == YES) {
            [self.backButton setImage:[UIImage imageNamed:@"back_black"] forState:UIControlStateNormal];
            self.parentLabel.textColor = [UIColor blackColor];
        }
    }else {
        NSArray *dataArr = dic[@"data"][@"media"];
        if (dataArr.count != 0) {
            NSDictionary *dic = dataArr[0];
            self.cellClassString = [NSString stringWithFormat:@"%@",dic[@"media_class_name"]];
            videoList = dic[@"list"];
        }
    }
    [self.dataArr removeAllObjects];
    [self.titleArr removeAllObjects];
    [self.heightArr removeAllObjects];
    self.selectedIndex = 0;
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    style.lineSpacing = 5;
    style.lineBreakMode = NSLineBreakByTruncatingTail;
    NSDictionary *attribute = @{NSParagraphStyleAttributeName : style, NSFontAttributeName:[UIFont systemFontOfSize:18 weight:UIFontWeightRegular]};
    
    for (int i = 0; i < videoList.count; i ++) {
        NSDictionary *dic = videoList[i];
        CurriculumModel *model = [[CurriculumModel alloc] initWithDic:dic];
        [self.dataArr addObject:model];
        NSString *title = [NSString stringWithFormat:@"%@",model.name];
        NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:title attributes:attribute];
        [attri addAttribute:NSKernAttributeName value:@(1) range:NSMakeRange(0, attri.length)];
        CGFloat height = [attri boundingRectWithSize:CGSizeMake(SCREEN_WIDTH - 64, 1000) options:NSStringDrawingUsesLineFragmentOrigin context:nil].size.height;
        [self.titleArr addObject:attri];
        [self.heightArr addObject:@(height)];
    }
    
    if(self.dataArr.count > 0) {
        self.tableView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    } else {
        self.tableView.backgroundColor = [UIColor whiteColor];
    }
    [self.tableView reloadData];
    
}
#pragma mark - Function

#pragma mark - Action
- (void)backAction {
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.selectedIndex inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
}
#pragma mark - Request
- (void)requestData {
    
    [self loadLocalData];
    
    if (self.isMenu) {
        [self requestMenuData];
        return;
    }
    
    NSString *filePath = [NSHomeDirectory() stringByAppendingString:[NSString stringWithFormat:@"/Documents/audio%@_%@_myJson.json",self.idString,self.tagString]];
    NSString* encodedString = [[NSString stringWithFormat:@"%@/api/index/AudioList?media_class_id=%@&tag=%@",server_addr,self.idString,self.tagString] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    __weak typeof(self) weakSelf = self;

    [self.objectAFNet getUrlStr:encodedString finish:^(id  _Nonnull dataString) {
        NSDictionary* dic = [NSJSONSerialization JSONObjectWithData:dataString options:NSJSONReadingMutableContainers error:nil];
        [dataString writeToFile:filePath atomically:YES];
        [weakSelf fillTheData:dic isNetRequest:YES];
    } andError:^(NSError * _Nonnull error) {
        
    }];
}

- (void)requestMenuData {
    __weak typeof(self) weakSelf = self;

    [self.objectAFNet getUrlStr:[NSString stringWithFormat:@"%@/api/home/getcatelist?id=%@&page=%@&pagesize=%@",server_addr,self.tagString,@"1",@"10000"] finish:^(id  _Nonnull dataString) {
        
        NSString *filePath = [NSHomeDirectory() stringByAppendingString:[NSString stringWithFormat:@"/Documents/getcatelist%@_myJson.json",self.idString]];
        [dataString writeToFile:filePath atomically:YES];

        NSDictionary* dic=[NSJSONSerialization JSONObjectWithData:dataString options:NSJSONReadingMutableContainers error:nil];

        [weakSelf fillTheData:dic isNetRequest:YES];
    } andError:^(NSError * _Nonnull error) {

    }];
}

- (void)loadLocalData {
    if (self.isMenu) {
        NSString *filePath = [NSHomeDirectory() stringByAppendingString:[NSString stringWithFormat:@"/Documents/getcatelist%@_myJson.json",self.tagString]];
            NSFileManager *fileManager = [NSFileManager defaultManager];
        if ([fileManager fileExistsAtPath:filePath]) {
            NSData* dataString = [NSData dataWithContentsOfFile:filePath];
            NSDictionary* dic = [NSJSONSerialization JSONObjectWithData:dataString options:NSJSONReadingMutableContainers error:nil];
            [self fillTheData:dic isNetRequest:NO];
        }
    }else {
        NSString *filePath = [NSHomeDirectory() stringByAppendingString:[NSString stringWithFormat:@"/Documents/audio%@_%@_myJson.json",self.idString,self.tagString]];
            NSFileManager *fileManager = [NSFileManager defaultManager];
        if ([fileManager fileExistsAtPath:filePath]) {
            NSData* dataString = [NSData dataWithContentsOfFile:filePath];
            NSDictionary* dic = [NSJSONSerialization JSONObjectWithData:dataString options:NSJSONReadingMutableContainers error:nil];
            [self fillTheData:dic isNetRequest:NO];
        }
    }
}
#pragma mark - UITableViewDelegate, UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 28 + 21 + 21;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] init];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (self.isMenu) {
//        return 300;
        return kHeaderH;
    }else{
        return topHeight + 36;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    if (self.isMenu) {
//        CGFloat height = 300;
        
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, kHeaderH)];
        [view addSubview:self.topBackView];
        [self.topImageView sd_setImageWithURL:[NSURL URLWithString:self.imageUrl] placeholderImage:[UIImage imageNamed:@"bg_main"]];

        // 圆角view
        UIView *cornerView = [[UIView alloc] initWithFrame:CGRectMake(0, kHeaderH - 30, SCREEN_WIDTH, 40)];
        cornerView.backgroundColor = [UIColor whiteColor];
        [view addSubview:cornerView];
        CAShapeLayer *layer = [[CAShapeLayer alloc] init];
        layer.frame = cornerView.bounds;
        layer.path = [UIBezierPath bezierPathWithRoundedRect:cornerView.bounds byRoundingCorners:UIRectCornerTopRight | UIRectCornerTopLeft cornerRadii:CGSizeMake(30, 30)].CGPath;
        cornerView.layer.mask = layer;
        
        // 封面图
        CGFloat contentHeight = kHeaderH - fkStatusAndNaBarH - 30; // 内容的高度 = 容器高度 - 状态栏和导航栏的高度 - 圆角占用的高度
        CGFloat imageWidth = 100;
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(16, fkStatusAndNaBarH + 15, imageWidth, imageWidth)];
        imageView.layer.cornerRadius = 16;
        imageView.layer.masksToBounds = YES;
        [view addSubview:imageView];
        [imageView sd_setImageWithURL:[NSURL URLWithString:self.imageUrl] placeholderImage:[UIImage imageNamed:@"bg_main"]];
        view.layer.zPosition = 0;
        
        // 标题
        UILabel *titleLabel = [[UILabel alloc] init];
        titleLabel.font = [UIFont systemFontOfSize:22 weight:UIFontWeightBold];
        titleLabel.textColor = [UIColor whiteColor];
        titleLabel.text = self.title;
        [view addSubview:titleLabel];
        
        // 描述
        UILabel *label = [[UILabel alloc] init];
        label.text = self.describe;
        label.numberOfLines = 2;
        label.font = [UIFont systemFontOfSize:17 weight:UIFontWeightBold];
        label.textColor = [UIColor whiteColor];
        [view addSubview:label];
        
        // 最后统一设置约束
        [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(imageView.mas_top).offset(0);
            make.left.equalTo(imageView.mas_right).offset(16);
            make.right.equalTo(@(-20));
            make.height.equalTo(@(20));
        }];
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(titleLabel.mas_bottom).offset(5);
            make.left.equalTo(imageView.mas_right).offset(16);
            make.right.equalTo(@(-20));
            make.bottom.equalTo(imageView).offset(-5);
        }];
        
        
        return view;
    }else {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, topHeight + 36)];
        view.backgroundColor = [UIColor whiteColor];
        UIView *cornerView = [[UIView alloc] initWithFrame:CGRectMake(0, topHeight + 6, SCREEN_WIDTH, 40)];
        cornerView.backgroundColor = [UIColor whiteColor];
        [view addSubview:cornerView];
        
        CAShapeLayer *layer = [[CAShapeLayer alloc] init];
        layer.frame = cornerView.bounds;
        layer.path = [UIBezierPath bezierPathWithRoundedRect:cornerView.bounds byRoundingCorners:UIRectCornerTopRight | UIRectCornerTopLeft cornerRadii:CGSizeMake(50, 50)].CGPath;
        view.layer.zPosition = 0;
        cornerView.layer.mask = layer;
        return view;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    AudioListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AudioListTableViewCell"];
    if (!cell) {
        cell = [[AudioListTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"AudioListTableViewCell"];
    }
    CurriculumModel *cellModel = self.dataArr[indexPath.row];
    cell.nameLabel.attributedText = self.titleArr[indexPath.row];
    cell.timeLabel.text = [GC_OCTool timeStrWithSecTime:[cellModel.audio_num integerValue]];
    if (!self.isMenu) {
        cell.classLabel.text = self.cellClassString;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    CurriculumModel *cellModel = self.dataArr[indexPath.row];
    self.selectedIndex = indexPath.row;

    
    BOOL isCache = NO;
    NSInteger indexNum1 = 0;
    for (int i = 0; i < self.cacheList.count; i++) {
        NSDictionary *d = self.cacheList[i];
        NSString *did = [NSString stringWithFormat:@"%@", d[@"id"]];
        if ([did isEqualToString:cellModel.id]) {
            indexNum1 = i;
            isCache = YES;
            break;
        }
    }
    
    if (isCache) {
        [SUPlayerManager manager].currentSongIndex = indexNum1;
        [SUPlayerManager manager].songList = self.cacheList;
    } else {
        self.tableView.userInteractionEnabled = NO;
        [[[ObjectAFNetWorking alloc]init] getUrlStr:[NSString stringWithFormat:@"%@/api/home/getcatelist?id=%@",server_addr, cellModel.media_class_id] finish:^(id  _Nonnull dataString) {

            NSDictionary* dic=[NSJSONSerialization JSONObjectWithData:dataString options:NSJSONReadingMutableContainers error:nil];
            NSArray *asss = dic[@"data"][@"list"];
            NSInteger indexNum = 0;
            for (int i = 0; i < asss.count; i++) {
                NSDictionary *d = asss[i];
                NSString *did = [NSString stringWithFormat:@"%@", d[@"id"]];
                if ([did isEqualToString:cellModel.id]) {
                    indexNum = i;
                    break;
                }
            }
            
            if (!((indexNum == [SUPlayerManager manager].currentSongIndex) && [asss isEqualToArray:[SUPlayerManager manager].songList])) {
                [SUPlayerManager manager].currentSongIndex = indexNum;
                [SUPlayerManager manager].songList = asss.mutableCopy;
                self.cacheList = asss.mutableCopy;
                
                [[UIApplication sharedApplication].keyWindow bringSubviewToFront:[SUPlayerManager manager].bottomView];
            }
            self.tableView.userInteractionEnabled = YES;
        } andError:^(NSError * _Nonnull error) {
            self.tableView.userInteractionEnabled = YES;
        }];
    }
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (self.isMenu) {
        self.headerView.alpha = scrollView.contentOffset.y/150.0;
    }else {
        self.headerView.alpha = 1;
    }
    if (scrollView.contentOffset.y < -StatusBarHeight) {
        [scrollView setContentOffset:CGPointMake(0, -StatusBarHeight) animated:NO];
    }
    if (scrollView.contentOffset.y > (SCREEN_HEIGHT - topHeight)) {
        self.button.hidden = NO;
    }else {
        self.button.hidden = YES;
    }
}
#pragma mark DZNEmptyDataSetDelegate & DZNEmptyDataSetSource
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView{
    return YES;
}

- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView{
    NSString *text = @"暂无内容";
    NSDictionary *attributes = @{
                                 NSFontAttributeName: [UIFont systemFontOfSize:15 weight:UIFontWeightRegular],
                                 NSForegroundColorAttributeName: [UIColor grayColor]};
    return [[NSAttributedString alloc] initWithString:text attributes:attributes];
}

#pragma mark - LazyLoad
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - topHeight) style:UITableViewStyleGrouped];
        if (@available(iOS 15.0, *)) {
            _tableView.sectionHeaderTopPadding = 0;
        }
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.emptyDataSetSource = self;
        _tableView.emptyDataSetDelegate = self;
        UINib *lib = [UINib nibWithNibName:@"AudioListTableViewCell" bundle:nil];
        [_tableView registerNib:lib forCellReuseIdentifier:@"AudioListTableViewCell"];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_HEIGHT, 60)];
    }
    return _tableView;
}

- (UIView *)headerView {
    if (!_headerView) {
        _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, topHeight)];
        _headerView.backgroundColor = fkMainColor;
        _headerView.alpha = 0.0;
        
    }
    return _headerView;
}

- (UIView *)topBackView {
    if (!_topBackView) {
        _topBackView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, kHeaderH)];
        [_topBackView addSubview:self.topImageView];
        
    }
    return _topBackView;
}

- (UIImageView *)topImageView {
    if (!_topImageView) {
        _topImageView = [[UIImageView alloc] initWithFrame:_topBackView.bounds];
        UIBlurEffect *blurEffrct =[UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
        UIVisualEffectView *visualEffectView = [[UIVisualEffectView alloc]initWithEffect:blurEffrct];
        visualEffectView.frame = _topImageView.bounds;
        
        [_topImageView addSubview:visualEffectView];
    }
    return _topImageView;
}

- (UIButton *)button {
    if (!_button) {
        _button = [UIButton buttonWithType:UIButtonTypeCustom];
        [_button setBackgroundImage:[UIImage imageNamed:@"dingwei"] forState:UIControlStateNormal];
        [_button addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
        _button.alpha = 0.5;
        _button.hidden = YES;
    }
    return _button;
}

- (UILabel *)parentLabel {
    if (!_parentLabel) {
        _parentLabel = ({
            UILabel *label = [[UILabel alloc] init];
            label.font = [UIFont systemFontOfSize:17 weight:UIFontWeightMedium];
            label.textColor = [UIColor whiteColor];
            label.text = self.parentName;
            
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(goBack)];
            label.userInteractionEnabled = YES;
            [label addGestureRecognizer:tap];
            
            label;
        });
    }
    return _parentLabel;
}
@end
